package drds.common.db.sql_mapping.configuration;

import drds.common.ShouldNeverHappenException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.InputStream;
import java.util.Locale;


public class XmlMappersEntityResolver implements EntityResolver {
    private static final String sql_mapper_dtd = "sql-mapper.dtd";
    private static final String sql_mapper_dtd_path = "drds/common/db/sql_mapping/dtd/sql-mapper.dtd";

    @Override
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
        String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
        if (lowerCaseSystemId.contains(sql_mapper_dtd)) {
            return getInputSource(sql_mapper_dtd_path, publicId, systemId);
        } else {
            throw new ShouldNeverHappenException();
        }
    }

    private InputSource getInputSource(String path, String publicId, String systemId) {
        InputSource inputSource = null;
        if (path != null) {
            InputStream inputStream = ClassLoader.getSystemResourceAsStream(path);
            inputSource = new InputSource(inputStream);
            inputSource.setPublicId(publicId);
            inputSource.setSystemId(systemId);
        }
        return inputSource;
    }

}
